import {Token}                  from '../utils/Storage';
import {DateFormat}             from '../utils/Format';
import {transVoucher}           from './voucher';
import {CALL_API, CART}         from "../constants";
import {postMethod, transform}  from "../utils/fetch";

function formatTime(time, format) {
    const dateTime = new Date(time);
    const o = {
        'M+': dateTime.getMonth() + 1, // month
        'd+': dateTime.getDate(), // day
        'h+': dateTime.getHours(), // hour
        'm+': dateTime.getMinutes(), // minute
        's+': dateTime.getSeconds(), // second
        'q+': Math.floor((dateTime.getMonth() + 3) / 3), // quarter
        S: dateTime.getMilliseconds(), // millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1,
            (`${dateTime.getFullYear()}`).substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
        if (new RegExp(`(${k})`).test(format)) {
            format = format.replace(RegExp.$1,
                RegExp.$1.length === 1 ? o[k] :
                (`00${o[k]}`).substr((`${o[k]}`).length));
        }
    }
    return format;
}

//获取商城列表信息
const fetchList = ({index, size}) => ({
    [CALL_API]: {
        url: `VMembers/selectVVouuchers?page=${index}&rows=${size}&m_id=${Token.getUserId()}`,
        types: CART.list.types(),
        extra: transform(transVoucher)
    }
});

//获取购物车列表
const fetchItem = () => ({
    [CALL_API]: {
        url: `VMembers/selectVShoppingCartByMId?m_id=${Token.getUserId()}`,
        types: CART.item.types(),
        extra: r => {
            var {count, list} = r.data;
            return Object.assign(r, {
                data: {
                    total: count,
                    list: _.map(list, transVoucher)
                }
            })
        }
    }
});

//获取兑换记录
const fetchRecords = ({index, size}) => ({
    [CALL_API]: {
        url: `VMembers/selectVMexchagngelogByMId?page=${index}&rows=${size}&m_id=${Token.getUserId()}`,
        types: CART.records.types(),
        extra: transform(
            ({
                 id,
                 shl,
                 dhsj,
                 dhjf,
                 yxfsl,
                 spmch,
             }) => (
                {
                    id: id.toString(),
                    name: spmch,
                    time: DateFormat.format(dhsj),
                    count: shl,
                    accumulate: dhjf,
                }))
    }
});

//修改数量
const fetchEdit = ({vId, count, qr, expire}) => ({
    [CALL_API]: {
        url: 'VMembers/insertVShoppingCart',
        types: CART.edit.types(),
        options: postMethod({
            shl: count,
            spid: vId,
            sptm: qr,
            sxrq: formatTime(expire,'yyyy-MM-dd hh:mm:ss'),
            m_id: Token.getUserId(),
        }),
    }
});

//兑换
const fetchExchange = () => ({
    [CALL_API]: {
        url: `VMembers/exchangeVShoppingCartByMId?m_id=${Token.getUserId()}`,
        types: CART.exchange.types(),
    }
});

//清空
const fetchClear = () => ({
    [CALL_API]: {
        url: `VMembers/updateVShoppingcartTo0ByMId?m_id=${Token.getUserId()}`,
        types: CART.clear.types(),
    }
});


export const edit = entity                          => dispatch => dispatch(fetchEdit(entity));
export const clear = ()                             => dispatch => dispatch(fetchClear());
export const loadItem = ()                          => dispatch => dispatch(fetchItem());
export const exchange = ()                          => dispatch => dispatch(fetchExchange());
export const loadList = page                        => dispatch => dispatch(fetchList(page));
export const loadRecords = page                     => dispatch => dispatch(fetchRecords(page));
